class Tagger
  @@found, @@skipped, @@indentical = 0, 0, 0

  def initialize
    @selection = OSA.app('iTunes').selection
    @artist = Artist.new
    @unique_artists = @selection.map { |s| s.artist }.uniq.length

    $stderr.puts "#{Color.error} Please select some tracks in iTunes" if @selection.empty?
  end

  def start
    puts "#{@selection.length} tracks selected and #{@unique_artists} unique artists."

    @selection.sort_by { |s| s.artist }.each_with_index do |track, idx|
      break if @input =~ /[aq]/
      # check if artist differs; if so, reinstantiate @artist
      if @artist.name.downcase != track.artist.strip.downcase
        @artist = Artist.new(track.artist)
        # no need to write tag if it is identical, therefore skip until artist differs
        if track.genre.strip.downcase == @artist.genre.downcase
          puts "#{Color.pass} Identical genres. Skipping..."
          @@indentical += 1
          @input = 'n'
        elsif @artist.genre == ''
          puts %{#{Color.pass} No tags found for "#{@artist.name}".}
          @@skipped += 1
          @input = 'n'
        else
          #puts "#{idx+1} out of #{@selection.length}"
          @input = confirm
        end
      end
      #puts %{#{Color.success} Writing tags...}
      track.genre = @artist.genre if @input == 'y'
    end
    puts "Done!\nTags Found:\t#{@@found}\nSkipped:\t#{@@skipped}\nIdentical:\t#{@@indentical}"
  end
  
  def confirm
    print %{#{Color.success} Most popular tag for "#{@artist.name}" is "#{@artist.genre}". }
    @@found += 1

    # add some space when in quiet mode
    if quiet?
      puts
      return 'y'
    end

    print %{Continue? (y/n/q) }
    gets.chomp.downcase
  end

  def quiet?
    ARGV[0] == '-q'
  end
end
